#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@File    ：auth_register.py
@Author  ：平
@Date    ：2025/9/28 11:01 
"""
import aiohttp
from fastapi import FastAPI

from app.config.config import settings
from app.exception.exception import AuthorizationException
from app.register.abstract_register import AbstractRegister
import logging

logger = logging.getLogger(__name__)


class AuthRegister(AbstractRegister):
    """
    认证注册类
    """

    def register(self, app: FastAPI):
        @app.middleware("http")
        async def auth_middleware(request, call_next):
            """
            认证中间件
            Args:
                request: 请求
                call_next: 下一个中间件

            Returns:

            """
            if request.url.path in settings.APPLICATION_AUTH_EXCLUDED_URL:
                return await call_next(request)
            # 获取请求头中的认证信息
            auth = request.headers.get("Authorization")
            if not auth:
                raise AuthorizationException("未授权")
            try:
                async with aiohttp.ClientSession() as session:
                    async with session.get(settings.BACKEND_SERVICE_URL + "/health",
                                           headers={"Authorization": auth}) as response:
                        response.raise_for_status()
                        body = await response.json()
                        if body.get("code") != 200:
                            raise AuthorizationException("未授权")
                        request.state.session = body.get("data")
            except Exception as e:
                logger.exception(f"认证失败:{e}")
                raise AuthorizationException("未授权")
            res = await call_next(request)
            request.state.session = None
            return res